DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only
A3Tech logo

Introduction to Python Programming · A3Tech

Module 5

Today you will

Store many products at once with lists and dictionaries, and use your Module 4 for loops to go through them.

  1. Store items in a list and look them up by position.
  2. Go through a list with a for loop, the same way as range() in Module 4.
  3. Add, change and remove items in a list.
  4. Store products and prices in a dictionary and look prices up by name.
  5. Use a dictionary and a list together to total an order.

Deep dive A: why do we need lists?

In Module 4 every variable held one value. But a shop has many products. Without a list, every item needs its own variable:

no_list.py
special1 = "Beef Patty"
special2 = "Coconut Tart"
special3 = "Sorrel Drink"
print(special1)
print(special2)
print(special3)
Output
Beef Patty
Coconut Tart
Sorrel Drink

Now add a fourth special, or forty. A list stores many values under one name: square brackets [ ], items separated by commas.

with_list.py
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
print(specials)
print(len(specials), "specials today")
Output
['Beef Patty', 'Coconut Tart', 'Sorrel Drink']
3 specials today
len() tells you how many items are in the list. It's the same len() you can use on text to count letters.
Lenght_cal.py
#lets calculate the lenght of items or strings
name = input("enter all your names: ")
for i in name:
    print(i.lower())
print(f"all of my names combined have {len(name)} letters in it") #using the len() built in function
Output
enter all your names: Ann Lee
a
n
n
 
l
e
e
all of my names combined have 7 letters in it

Deep dive B: positions (the index)

Every item in a list has a position, called its index. Python starts counting at 0, not 1.

IndexItemCounting from the end
0Beef Patty-3
1Coconut Tart-2
2Sorrel Drink-1
index.py
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
print(specials[0])     # the first item
print(specials[1])
print(specials[-1])    # -1 is always the last item
Output
Beef Patty
Coconut Tart
Sorrel Drink

Ask for a position that doesn't exist, and Python stops with an IndexError:

index_error.py
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
print(specials[3])
Output
Traceback (most recent call last):
  File "index_error.py", line 2, in <module>
    print(specials[3])
          ~~~~~~~~^^^
IndexError: list index out of range

Deep dive C: flashback - for loops on a list

In Module 4 you wrote for qty in range(1, 11): and for letter in "PATTY":. A for loop works exactly the same way on a list: it runs once for each item, in order, and the loop variable takes the next item each time.

LoopThe variable takes...Module
for qty in range(1, 4):1, then 2, then 34
for letter in "PATTY":P, A, T, T, Y4
for item in specials:each product in the list5
for_list.py
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
for item in specials:
    print("Today:", item)
print("That's all the specials")
Output
Today: Beef Patty
Today: Coconut Tart
Today: Sorrel Drink
That's all the specials

The running total from the Module 4 checkout works on a list too: start at 0 before the loop, add inside it.

list_total.py
prices = [5.00, 4.00, 3.50, 5.00]
total = 0
for price in prices:
    total += price
print("Items:", len(prices))
print(f"Total: EC${total:.2f}")
print(f"Average: EC${total / len(prices):.2f}")
Output
Items: 4
Total: EC$17.50
Average: EC$4.38

Python has shortcuts for the most common jobs: sum(), max() and min().

shortcuts.py
prices = [5.00, 4.00, 3.50, 5.00]
print("Total:", sum(prices))
print("Most expensive:", max(prices))
print("Cheapest:", min(prices))
Output
Total: 17.5
Most expensive: 5.0
Cheapest: 3.5
auto_calc.py
collection = []

for i in range(5):
    num = int(input(f"Enter number {i+1}: "))
    collection.append(num)

print("The sum is:", sum(collection))
print("the highest # you entered was", max(collection))
print("the lowest # you entered was", min(collection))
print("the average was", sum(collection) / len(collection))
Output
Enter number 1: 5
Enter number 2: 10
Enter number 3: 15
Enter number 4: 20
Enter number 5: 25
The sum is: 75
the highest # you entered was 25
the lowest # you entered was 5
the average was 15.0

Deep dive D: changing a list

A list can change while the program runs. The dot means "do this to the list", just like .lower() on text in Module 3.

  • order.append(x) adds x to the end
  • order.remove(x) takes out the first x it finds
  • order[0] = x replaces the item at position 0
  • x in order asks a True/False question: is x in the list?
change_list.py
order = ["Beef Patty", "Coconut Tart"]
order.append("Sorrel Drink")      # customer adds a drink
print(order)
order[0] = "Cheese Patty"         # swap the beef for cheese
print(order)
order.remove("Coconut Tart")      # changed their mind
print(order)
print("Sorrel Drink" in order)
print("Coconut Tart" in order)
Output
['Beef Patty', 'Coconut Tart', 'Sorrel Drink']
['Cheese Patty', 'Coconut Tart', 'Sorrel Drink']
['Cheese Patty', 'Sorrel Drink']
True
False

Start with an empty list [] and fill it inside a loop. This is the Module 4 checkout again, but now it remembers every price instead of forgetting it:

checkout_list.py
prices = []
while True:
    entry = input("Item price (or 'done'): ")
    if entry == "done":
        break
    prices.append(float(entry))

print("You bought", len(prices), "items:", prices)
print(f"Total: EC${sum(prices):.2f}")
print(f"Most expensive item: EC${max(prices):.2f}")
Output
Item price (or 'done'): 5
Item price (or 'done'): 4
Item price (or 'done'): 3.50
Item price (or 'done'): done
You bought 3 items: [5.0, 4.0, 3.5]
Total: EC$12.50
Most expensive item: EC$5.00

Deep dive E: dictionaries - look things up by name

A list finds things by position. But at the till nobody asks "what's the price of item number 2?" They ask "how much is a coconut tart?"

A dictionary stores pairs: a key (the name) and a value (the price). Curly brackets { }, a colon between each key and its value, commas between pairs.

dict_basic.py
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00}
print(products["Coconut Tart"])
print(len(products), "products")
Output
4.0
3 products

To add a product or change a price, put the key in square brackets and use =. A new key adds a pair. A key that's already there gets its value replaced.

dict_change.py
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
products["Sorrel Drink"] = 3.50     # new key: adds a product
products["Beef Patty"] = 5.50       # existing key: changes the price
print(products)
Output
{'Beef Patty': 5.5, 'Coconut Tart': 4.0, 'Sorrel Drink': 3.5}

Keys must match exactly, like == in Module 3. A typo or different capitals gives a KeyError:

key_error.py
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
print(products["coconut tart"])
Output
Traceback (most recent call last):
  File "key_error.py", line 2, in <module>
    print(products["coconut tart"])
          ~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'coconut tart'

So check first. in works on dictionaries too, and it checks the keys:

dict_in.py
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
#item = "Bread Pudding"
item = input("Enter Item To Search") #alternative way to search
if item in products:
    print(item, "costs EC$", products[item])
else:
    print("Sorry, we don't sell", item)
Output
Sorry, we don't sell Bread Pudding

Deep dive F: looping through a dictionary

A for loop on a dictionary gives you each key. Add .items() and you get the key and the value together, so the loop has two variables separated by a comma.

dict_loop.py
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00}
for name in products:
    print(name)

print("-" * 22)
for name, price in products.items(): #.items is how we pull the product list
    print(f"{name:<14} EC${price:5.2f}")

# Third loop: prints just the prices
#for price in products.values(): #products.values() is how we pull the price
    #print(f"EC${price:5.2f}")
Output
Beef Patty
Cheese Patty
Coconut Tart
----------------------
Beef Patty     EC$ 5.00
Cheese Patty   EC$ 5.00
Coconut Tart   EC$ 4.00

Deep dive G: list or dictionary?

UseWhenShop example
list [ ]Order matters, or the same thing can appear more than onceThe items on the counter: 2 beef patties appear twice
dictionary { }You look things up by a nameThe price list, or stock count for each product

Deep dive H: both together - a receipt

Real shop code uses both: the dictionary is the price list, the list is what this customer is buying. The loop goes through the order, looks up each price, and keeps a running total.

receipt_preview.py
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00, "Sorrel Drink": 3.50}
order = ["Beef Patty", "Beef Patty", "Sorrel Drink", "Coconut Tart"]

total = 0
for item in order:
    price = products[item]
    total += price
    print(f"{item:<14} EC${price:5.2f}")
print("-" * 23)
print(f"{'TOTAL':<14} EC${total:5.2f}")
Output
Beef Patty     EC$ 5.00
Beef Patty     EC$ 5.00
Sorrel Drink   EC$ 3.50
Coconut Tart   EC$ 4.00
-----------------------
TOTAL          EC$17.50

1. Lists and dictionaries

A list of specials and a dictionary of prices.

01_products.py
# Module 5 - lists and dictionaries
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]     # a list
print("Today's specials:", specials[0], "and", len(specials) - 1, "more")
specials.append("Bread Pudding")
for item in specials:
    print("-", item)

products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00}   # a dictionary
print("A coconut tart costs EC$", products["Coconut Tart"])
products["Sorrel Drink"] = 3.50       # add a new product
for name, price in products.items():
    print(f"{name:<14} EC${price:.2f}")
Output
Today's specials: Beef Patty and 2 more
- Beef Patty
- Coconut Tart
- Sorrel Drink
- Bread Pudding
A coconut tart costs EC$ 4.0
Beef Patty     EC$5.00
Cheese Patty   EC$5.00
Coconut Tart   EC$4.00
Sorrel Drink   EC$3.50

2. Take an order

The menu is a dictionary, the order is a list, and the while loop from Module 4 keeps taking items until the customer types done.

02_order.py
# Module 5 - take an order: a dictionary for prices, a list for the order
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00, "Sorrel Drink": 3.50}
order = []

print("MENU")
for name, price in products.items():
    print(f"  {name:<14} EC${price:5.2f}")

while True:
    item = input("Add item (or 'done'): ")
    if item == "done":
        break
    if item in products:
        order.append(item)
        print("  Added", item)
    else:
        print("  Sorry, we don't sell", item)

total = 0
for item in order:
    total += products[item]
print(f"{len(order)} items. Total: EC${total:.2f}")
Output
MENU
  Beef Patty     EC$ 5.00
  Cheese Patty   EC$ 5.00
  Coconut Tart   EC$ 4.00
  Sorrel Drink   EC$ 3.50
Add item (or 'done'): Beef Patty
  Added Beef Patty
Add item (or 'done'): Sorrel Drink
  Added Sorrel Drink
Add item (or 'done'): Pizza
  Sorry, we don't sell Pizza
Add item (or 'done'): Beef Patty
  Added Beef Patty
Add item (or 'done'): done
3 items. Total: EC$13.50

print(f" {name:<14} EC${price:5.2f}") - Reminder that <14 reserves 14 character length for the name, and :5.2f reserves 5 character spaces for the price and .2f is for 2 decimal places in the currency format

Bug hunt

This program crashes, and it has 2 bugs. Read the last line of the error, fix that bug, run it again.

03_list_bug.py
# BUG HUNT - this program crashes. There are 2 bugs.
# It should print all 3 specials, then the price of a coconut tart.
# 1. Run it.  2. Read the LAST line of the error.  3. Fix that one bug.  4. Repeat.
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
for i in range(1, 4):
    print(specials[i])

products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
print("A coconut tart costs EC$", products["Coconut tart"])
Hints (open only if stuck)
  1. Where does a list start counting?
  2. How many positions does a 3-item list have, and what are they?
  3. Dictionary keys have to match exactly, capitals too.

Words to know

WordMeaning
ListMany values in order, in square brackets: ["Beef Patty", "Coconut Tart"]
IndexA position in a list, starting at 0: specials[0]
len()How many items are in a list (or letters in text)
.append()Adds an item to the end of a list
.remove()Takes an item out of a list
inAsks True/False: is it in the list (or a key in the dictionary)?
DictionaryPairs of key and value, in curly brackets: {"Beef Patty": 5.00}
Key / valueThe name you look up / the answer you get back
.items()Gives each key and value together in a for loop

Practice

Homework 5 (5%): price_list.py

A till for your own shop. It must:

Submit your .py file and a screenshot of it running, before the next module.

MarkMeans
5Runs and has everything
3Runs with parts missing, or has errors
1Started
0Not submitted

Quiz 5

Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).

1. What does this print?
specials = ["Patty", "Tart", "Juice"]
print(specials[1])
2. What does this print?
prices = {"Patty": 5.0, "Tart": 4.0}
print(prices["Tart"])
3. What does this print?
prices = [5.0, 4.0, 3.5]
total = 0
for p in prices:
    total += p
print(total)
4. What does this print?
specials = ["Patty", "Tart", "Juice"]
print(specials[3])
5. What does specials.append("Pudding") do?

ADDITIONAL - STREAMLIT APP - SNEAK PEEK 5

Everything from today, plus Modules 3 and 4, as a web page. The menu is a dictionary, the customer picks items (Streamlit hands them back as a list), a for loop builds the receipt with a running total, and if / elif gives the party discount.

order_app.py
# order_app.py - lists, dictionaries, loops and if/elif in a Streamlit app
# Run it with:  streamlit run order_app.py

import streamlit as st

st.title("Mama J's Bakery - Order Builder")

products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00,
            "Sorrel Drink": 3.50, "Bread Pudding": 6.00}               # Module 5: a dictionary

st.subheader("Menu")
for name, price in products.items():                                  # Module 5: .items()
    st.write(f"{name}: EC${price:.2f}")                                # Module 4: f-strings

chosen = st.multiselect("What would you like?", list(products))      # gives back a LIST

total = 0                                                             # Module 4: running total
items = 0
for name in chosen:                                                   # Module 4 + 5: for over a list
    qty = st.number_input(f"How many {name}?", min_value=1, value=1, step=1, key=name)
    line = products[name] * qty                                       # Module 5: look up the price
    total += line
    items += qty
    st.write(f"{qty} x {name} = EC${line:.2f}")

if items >= 12:                                                       # Module 3: if / elif / else
    total = total * 0.85
    st.success("Party order: 15% off!")
elif items >= 6:
    total = total * 0.90
    st.info("Big order: 10% off!")
elif items == 0:
    st.warning("Pick something from the menu.")

st.subheader(f"Total: EC${total:.2f} for {items} items")
Output
See the browser. Pick Beef Patty and Sorrel Drink, then set them to 4 and 2:
4 x Beef Patty = EC$20.00
2 x Sorrel Drink = EC$7.00
Big order: 10% off!
Total: EC$24.30 for 6 items

Change Beef Patty to 10: Party order: 15% off!  Total: EC$48.45 for 12 items